package tests.app;

import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import qq2564874169.tuaotuao.fx.FxDate;
import qq2564874169.tuaotuao.fx.app.ro.ROContext;
import qq2564874169.tuaotuao.fx.app.so.DefaultServiceContext;
import qq2564874169.tuaotuao.fx.app.so.ServiceContext;
import qq2564874169.tuaotuao.fx.concurrent.FxCountDownLatch;
import qq2564874169.tuaotuao.fx.context.BeanContext;

import java.io.IOException;

@Configuration
public class Beans {
    @Bean
    @Scope(BeanContext.SCOPE_CONTEXT)
    public ServiceContext getServiceContext(ApplicationContext ctx) {
        return new DefaultServiceContext(ctx);
    }

    @Bean
    @Scope(BeanContext.SCOPE_CONTEXT)
    public ROContext getROContext(ApplicationContext appctx) {
        return new ROContext(appctx);
    }

    @Bean
    @Scope(BeanContext.SCOPE_SINGLETON)
    public ZooKeeper getZk() throws IOException {
        var latch = new FxCountDownLatch(1);
        ZooKeeper zk = new ZooKeeper("192.168.118.132:2181", (int) FxDate.toMillisByHours(1), e -> {
            if (e.getState().equals(Watcher.Event.KeeperState.SyncConnected)) {
                latch.countDown();
            } else {
                latch.countDown(new RuntimeException(e.getState().toString()));
            }
        });
        latch.await();
        return zk;
    }
}
